import logging
from logging.handlers import RotatingFileHandler
import os


class AppLog:
    _instance = None
    _initialized = False

    def __new__(cls):
        if not cls._instance:
            cls._instance = super().__new__(cls)
        return cls._instance

    def __init__(self):
        if not self._initialized:
            self._configure_logging()
            self._initialized = True

    def _configure_logging(self):
        """日志系统配置"""
        # 基础配置
        log_dir = "logs"
        # print(f"当前工作目录: {os.getcwd()}")
        # print(f"日志目录: {os.path.abspath(log_dir)}")
        os.makedirs(log_dir, exist_ok=True)
        formatter = logging.Formatter(
            '%(asctime)s [%(name)s] %(levelname)s - %(message)s',
            datefmt='%Y-%m-%d %H:%M:%S'
        )

        # 文件处理器（50MB轮转，保留3份）
        file_handler = RotatingFileHandler(
            filename=os.path.join(log_dir, 'app.log'),
            maxBytes=50*1024*1024,
            backupCount=3,
            encoding='utf-8'
        )
        file_handler.setLevel(logging.DEBUG)
        file_handler.setFormatter(formatter)

        # 控制台处理器
        console_handler = logging.StreamHandler()
        console_handler.setLevel(logging.INFO)
        console_handler.setFormatter(formatter)

        # 配置根日志
        root_logger = logging.getLogger()
        root_logger.setLevel(logging.DEBUG)
        root_logger.addHandler(file_handler)
        root_logger.addHandler(console_handler)

    @staticmethod
    def get_logger(name=None):
        """获取日志器"""
        return logging.getLogger(name)